﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dxr.Police.IACS.Models;
using Zongsoft.Data;

namespace Dxr.Police.IACS.FullText
{
    public class DataSourceProvider : Zongsoft.Collections.Collection<IDataSource>, IDataSource
    {
        public bool CanUse(DataType type)
        {
            return this.Any(p => p.CanUse(type));
        }

        public int ImportFromExcel(string path, DataType type, Dxr.Police.Models.UserInfo user)
        {
            var source = this.FirstOrDefault(p => p.CanUse(type));

            if (source == null)
                return 0;

            return source.ImportFromExcel(path, type, user);
        }

        public IEnumerable<FullTextModel> Select(FullTextConditional condition, Paging paging)
        {
            var results = new List<FullTextModel>();
            long count = 0;

            object lockObj = new object();

            var tasks = new List<Task>();

            foreach (var item in this)
            {
                tasks.Add(Task.Factory.StartNew((p) =>
                {
                    var pg = new Paging(paging.PageIndex, paging.PageSize);
                    var temp = ((IDataSource)p).Select(condition, pg);
                    lock (lockObj)
                    {
                        results.AddRange(temp);
                        count += pg.TotalCount;
                    }
                }, item));
            }

            Task.Factory.ContinueWhenAll(tasks.ToArray(), p =>
            {
                foreach (var item in p)
                    item.Dispose();
            }).Wait();

            paging.TotalCount = count;

            return results.OrderByDescending(p => p.OrderTime).ToList();
        }
    }
}
